document.addEventListener('DOMContentLoaded', function() {
    // 文件上传交互
    const dropArea = document.getElementById('drop-area');
    const fileInput = document.getElementById('file-input');
    const shareBtn = document.getElementById('share-btn');
    const uploadResult = document.getElementById('upload-result');
    const downloadForm = document.getElementById('download-form');
    const downloadResult = document.getElementById('download-result');
    
    // 确保元素存在
    if (!dropArea || !fileInput || !shareBtn || !uploadResult || !downloadForm || !downloadResult) {
        console.error('无法找到必要的DOM元素');
        return;
    }
    
    // 存储选择的文件
    let selectedFile = null;
    
    // 点击上传区域触发文件选择
    dropArea.addEventListener('click', () => {
        fileInput.click();
    });
    
    // 拖放功能
    ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
        dropArea.addEventListener(eventName, preventDefaults, false);
    });
    
    function preventDefaults(e) {
        e.preventDefault();
        e.stopPropagation();
    }
    
    ['dragenter', 'dragover'].forEach(eventName => {
        dropArea.addEventListener(eventName, highlight, false);
    });
    
    ['dragleave', 'drop'].forEach(eventName => {
        dropArea.addEventListener(eventName, unhighlight, false);
    });
    
    function highlight() {
        dropArea.style.borderColor = '#4361ee';
        dropArea.style.backgroundColor = 'rgba(67, 97, 238, 0.05)';
    }
    
    function unhighlight() {
        dropArea.style.borderColor = '#e9ecef';
        dropArea.style.backgroundColor = '';
    }
    
    // 处理文件放置
    dropArea.addEventListener('drop', handleDrop, false);
    
    function handleDrop(e) {
        const dt = e.dataTransfer;
        const files = dt.files;
        handleFiles(files);
    }
    
    // 处理文件选择
    fileInput.addEventListener('change', function() {
        handleFiles(this.files);
    });
    
    function handleFiles(files) {
        if (files.length > 0) {
            const file = files[0];
            const fileSizeMB = (file.size / (1024 * 1024)).toFixed(2);
            
            // 存储选择的文件
            selectedFile = file;
            
            // 更新UI显示文件信息
            dropArea.innerHTML = `
                <div class="upload-icon">
                    <i class="fas fa-file"></i>
                </div>
                <div class="upload-text">${file.name}</div>
                <div class="upload-hint">${fileSizeMB} MB</div>
            `;
        }
    }
    
    // 生成分享链接按钮
    shareBtn.addEventListener('click', function() {
        if (!selectedFile) {
            showMessage('请先选择要分享的文件', 'error');
            return;
        }
        
        // 显示加载状态
        shareBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 处理中...';
        shareBtn.disabled = true;
        
        // 获取表单数据
        const formData = new FormData();
        formData.append('file', selectedFile);
        formData.append('expire_days', document.getElementById('expire-days').value);
        formData.append('max_downloads', document.getElementById('max-downloads').value);
        
        // 发送AJAX请求
        fetch('/share', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            // 恢复按钮状态
            shareBtn.innerHTML = '<i class="fas fa-share-alt"></i> 生成分享链接';
            shareBtn.disabled = false;
            
            if (data.success) {
                // 显示分享结果
                uploadResult.innerHTML = `
                    <div class="alert alert-success">
                        <i class="fas fa-check-circle alert-icon"></i>
                        <div>
                            <h3>分享成功!</h3>
                            <p>您的文件已成功上传并生成提取码</p>
                            <div style="background: #eaf2ff; padding: 1.5rem; border-radius: 12px; display: inline-block; margin: 1.5rem 0;">
                                <div style="font-size: 2.5rem; font-weight: 700; letter-spacing: 5px; color: #4361ee;">${data.access_code}</div>
                            </div>
                            <p>文件名: ${data.filename}</p>
                            <p>文件大小: ${(data.file_size / (1024 * 1024)).toFixed(2)} MB</p>
                            <p>有效期至: ${data.expire_time}</p>
                            <p>最大下载次数: ${data.max_downloads}次</p>
                        </div>
                    </div>
                    <div class="text-center">
                        <button class="btn btn-primary" onclick="copyToClipboard('${data.access_code}')">
                            <i class="fas fa-copy"></i> 复制提取码
                        </button>
                        <button class="btn btn-outline" style="margin-left: 1rem;" onclick="location.reload()">
                            <i class="fas fa-redo"></i> 分享新文件
                        </button>
                    </div>
                `;
            } else {
                showMessage(data.message, 'error');
            }
        })
        .catch(error => {
            // 恢复按钮状态
            shareBtn.innerHTML = '<i class="fas fa-share-alt"></i> 生成分享链接';
            shareBtn.disabled = false;
            
            showMessage('文件上传失败，请重试', 'error');
            console.error('上传错误:', error);
        });
    });
    
    // 文件下载表单提交
    downloadForm.addEventListener('submit', function(e) {
        e.preventDefault();
        const accessCode = document.getElementById('access-code').value.trim().toUpperCase();
        
        if (!accessCode) {
            showMessage('请输入提取码', 'error', downloadResult);
            return;
        }
        
        // 显示加载状态
        const downloadBtn = document.querySelector('.download-btn');
        const originalBtnText = downloadBtn.innerHTML;
        downloadBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 处理中...';
        downloadBtn.disabled = true;
        
        // 发送AJAX请求
        fetch('/download', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: `access_code=${accessCode}`
        })
        .then(response => {
            // 恢复按钮状态
            downloadBtn.innerHTML = originalBtnText;
            downloadBtn.disabled = false;
            
            if (response.ok) {
                // 从响应头中获取文件名
                const contentDisposition = response.headers.get('Content-Disposition');
                let filename = 'file';
                
                if (contentDisposition) {
                    const filenameMatch = contentDisposition.match(/filename\*?=['"]?(?:UTF-\d['"]*)?([^;\n]*)['"]?/i);
                    if (filenameMatch && filenameMatch[1]) {
                        filename = decodeURIComponent(filenameMatch[1]);
                    }
                }
                
                return response.blob().then(blob => {
                    // 创建下载链接
                    const url = window.URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = filename;
                    document.body.appendChild(a);
                    a.click();
                    window.URL.revokeObjectURL(url);
                    document.body.removeChild(a);
                    
                    // 显示成功消息
                    showMessage('文件下载成功', 'success', downloadResult);
                });
            } else {
                return response.json().then(data => {
                    showMessage(data.message, 'error', downloadResult);
                });
            }
        })
        .catch(error => {
            // 恢复按钮状态
            downloadBtn.innerHTML = originalBtnText;
            downloadBtn.disabled = false;
            
            showMessage('文件下载失败，请重试', 'error', downloadResult);
            console.error('下载错误:', error);
        });
    });
    
    // 显示消息提示
    function showMessage(message, type, container = uploadResult) {
        container.innerHTML = `
            <div class="alert alert-${type}">
                <i class="fas fa-${type === 'success' ? 'check-circle' : 'exclamation-triangle'} alert-icon"></i>
                <div>${message}</div>
            </div>
        `;
        
        // 5秒后自动消失
        setTimeout(() => {
            container.innerHTML = '';
        }, 5000);
    }
});

// 复制提取码到剪贴板（全局函数）
function copyToClipboard(text) {
    navigator.clipboard.writeText(text).then(() => {
        const uploadResult = document.getElementById('upload-result');
        if (uploadResult) {
            uploadResult.innerHTML = `
                <div class="alert alert-success">
                    <i class="fas fa-check-circle alert-icon"></i>
                    <div>提取码已复制到剪贴板!</div>
                </div>
            `;
            setTimeout(() => {
                uploadResult.innerHTML = '';
            }, 3000);
        }
    }, (err) => {
        console.error('复制失败:', err);
        const uploadResult = document.getElementById('upload-result');
        if (uploadResult) {
            uploadResult.innerHTML = `
                <div class="alert alert-error">
                    <i class="fas fa-exclamation-triangle alert-icon"></i>
                    <div>复制失败，请手动复制</div>
                </div>
            `;
        }
    });
}